<template>
    <div class="game-container">
        <div class="game-header">
            <div class="sun-count">阳光: {{ sunCount }}</div>
            <div class="score">得分: {{ score }}</div>
            <div class="game-controls">
                <button
                    v-if="!isGameStarted && !gameOver"
                    @click="startGame"
                    class="control-btn"
                >
                    开始游戏
                </button>
                <button
                    v-if="isGameStarted && !gameOver"
                    @click="pauseGame"
                    class="control-btn"
                >
                    暂停
                </button>
                <button
                    v-if="!isGameStarted && !gameOver"
                    @click="resumeGame"
                    class="control-btn"
                >
                    继续
                </button>
            </div>
        </div>

        <div class="game-board">
            <div class="plant-selector">
                <div
                    v-for="plant in getAvailablePlants()"
                    :key="plant.id"
                    class="plant-card"
                    :class="{
                        disabled: sunCount < plant.cost || !isGameStarted,
                    }"
                    @click="selectPlant(plant)"
                >
                    <img :src="plant.image" :alt="plant.name" />
                    <div class="cost">{{ plant.cost }}</div>
                    <div class="plant-name">{{ plant.name }}</div>
                    <div class="plant-description">{{ plant.description }}</div>
                </div>
            </div>

            <div class="game-grid">
                <div v-for="row in 5" :key="row" class="grid-row">
                    <div
                        v-for="col in 9"
                        :key="col"
                        class="grid-cell"
                        @click="placePlant(row - 1, col - 1)"
                    >
                        <Plant
                            v-if="plants[row - 1][col - 1]"
                            :plant="plants[row - 1][col - 1]"
                            :row="row - 1"
                            :col="col - 1"
                            :zombies="gameLogicRef?.zombies || []"
                            @attack="handlePlantAttack"
                            ref="plantRefs"
                        />
                    </div>
                </div>
            </div>
        </div>

        <GameLogic ref="gameLogicRef" />

        <div v-if="gameOver" class="game-over">
            <h2>游戏结束</h2>
            <p>最终得分: {{ score }}</p>
            <button @click="startGame" class="restart-btn">重新开始</button>
        </div>
    </div>
</template>

<script setup>
import { ref, onMounted, onUnmounted } from "vue";
import Plant from "./components/Plant.vue";
import GameLogic from "./components/GameLogic.vue";

const sunCount = ref(100);
const score = ref(0);
const selectedPlant = ref(null);
const plantRefs = ref([]);
const gameLogicRef = ref(null);
const gameOver = ref(false);
const isGameStarted = ref(false);

const availablePlants = [
    {
        id: 1,
        name: "向日葵",
        cost: 50,
        image: "/plants/sunflower.svg",
        description: "产生阳光",
    },
    {
        id: 2,
        name: "豌豆射手",
        cost: 100,
        image: "/plants/peashooter.svg",
        description: "发射豌豆",
    },
    {
        id: 3,
        name: "坚果墙",
        cost: 50,
        image: "/plants/wallnut.svg",
        description: "防御僵尸",
    },
    {
        id: 4,
        name: "双发射手",
        cost: 200,
        image: "/plants/peashooter.svg",
        description: "发射双倍豌豆",
        unlockedAt: 2,
    },
    {
        id: 5,
        name: "寒冰射手",
        cost: 175,
        image: "/plants/iceshooter.svg",
        description: "发射冰冻豌豆",
        unlockedAt: 3,
    },
];

const selectPlant = (plant) => {
    if (sunCount.value >= plant.cost) {
        selectedPlant.value = plant;
    }
};

const placePlant = (row, col) => {
    if (selectedPlant.value && !plants[row][col] && isGameStarted.value) {
        plants[row][col] = { ...selectedPlant.value };
        sunCount.value -= selectedPlant.value.cost;
        selectedPlant.value = null;
    }
};

// 初始化5x9的游戏网格
const plants = Array(5)
    .fill()
    .map(() => Array(9).fill(null));

// 处理植物攻击
const handlePlantAttack = (attackData) => {
    if (attackData.type === "sun") {
        // 阳光产生，每次增加25点阳光
        sunCount.value += 25;
    } else {
        // 攻击僵尸
        const zombies = gameLogicRef.value.zombies;

        if (attackData.zombieId) {
            // 直接攻击指定僵尸
            const killed = gameLogicRef.value.takeDamage(
                attackData.zombieId,
                attackData.damage,
                attackData.freezeDuration || 0
            );
            if (killed) {
                score.value += 100;
            }
        } else {
            // 旧的攻击逻辑，遍历所有僵尸
            zombies.forEach((zombie) => {
                if (zombie.row === attackData.row) {
                    const killed = gameLogicRef.value.takeDamage(
                        zombie.id,
                        attackData.damage,
                        attackData.freezeDuration || 0
                    );
                    if (killed) {
                        score.value += 100;
                    }
                }
            });
        }
    }
};

// 检查游戏是否结束
const checkGameOver = () => {
    const zombies = gameLogicRef.value.zombies;
    return zombies.some((zombie) => zombie.x <= 0);
};

// 检查是否过关
const checkLevelComplete = () => {
    return (
        gameLogicRef.value.zombiesLeft === 0 &&
        gameLogicRef.value.zombies.length === 0
    );
};

// 游戏主循环
let gameLoop;
onMounted(() => {
    gameLoop = setInterval(() => {
        if (checkGameOver()) {
            gameOver.value = true;
            clearInterval(gameLoop);
            gameLogicRef.value.stopGame();
        } else if (checkLevelComplete()) {
            gameLogicRef.value.nextLevel();
        }
    }, 500); // 降低游戏循环频率到500ms
});

let sunDropInterval;
let naturalSunInterval;

// 开始游戏
const startGame = () => {
    // 重置游戏状态
    sunCount.value = 100;
    score.value = 0;
    gameOver.value = false;
    isGameStarted.value = true;

    // 清空植物
    for (let i = 0; i < 5; i++) {
        for (let j = 0; j < 9; j++) {
            plants[i][j] = null;
        }
    }

    // 停止所有定时器
    clearInterval(sunDropInterval);
    clearInterval(naturalSunInterval);

    gameLogicRef.value.startGame();

    // 每隔15秒自然掉落一个阳光
    sunDropInterval = setInterval(() => {
        if (isGameStarted.value && !gameOver.value) {
            sunCount.value += 25;
        }
    }, 5000);

    // 每隔10秒检查一次向日葵
    naturalSunInterval = setInterval(() => {
        if (isGameStarted.value && !gameOver.value) {
            // 限制最大阳光数量为999
            if (sunCount.value >= 999) return;

            // 计算向日葵数量
            let sunflowerCount = 0;
            for (let i = 0; i < 5; i++) {
                for (let j = 0; j < 9; j++) {
                    if (plants[i][j] && plants[i][j].name === "向日葵") {
                        sunflowerCount++;
                    }
                }
            }

            // 每个向日葵产生25点阳光，但不超过最大限制
            const newSun = Math.min(sunflowerCount * 25, 999 - sunCount.value);
            if (newSun > 0) {
                sunCount.value += newSun;
            }
        }
    }, 10000);
};

// 暂停游戏
const pauseGame = () => {
    isGameStarted.value = false;
    gameLogicRef.value.stopGame();
    clearInterval(sunDropInterval);
    clearInterval(naturalSunInterval);
};

// 继续游戏
const resumeGame = () => {
    isGameStarted.value = true;
    gameLogicRef.value.startGame();

    // 停止所有定时器
    clearInterval(sunDropInterval);
    clearInterval(naturalSunInterval);

    // 重新启动阳光系统
    sunDropInterval = setInterval(() => {
        if (isGameStarted.value && !gameOver.value) {
            if (sunCount.value < 999) {
                sunCount.value += 25;
            }
        }
    }, 15000);

    naturalSunInterval = setInterval(() => {
        if (isGameStarted.value && !gameOver.value) {
            // 限制最大阳光数量为999
            if (sunCount.value >= 999) return;

            // 计算向日葵数量
            let sunflowerCount = 0;
            for (let i = 0; i < 5; i++) {
                for (let j = 0; j < 9; j++) {
                    if (plants[i][j] && plants[i][j].name === "向日葵") {
                        sunflowerCount++;
                    }
                }
            }

            // 每个向日葵产生25点阳光，但不超过最大限制
            const newSun = Math.min(sunflowerCount * 25, 999 - sunCount.value);
            if (newSun > 0) {
                sunCount.value += newSun;
            }
        }
    }, 10000);
};

// 获取可用植物
const getAvailablePlants = () => {
    if (!isGameStarted.value) {
        return availablePlants;
    }

    const currentLevel = gameLogicRef.value?.currentLevel || 1;
    return availablePlants.filter(
        (plant) => !plant.unlockedAt || plant.unlockedAt <= currentLevel
    );
};

onUnmounted(() => {
    clearInterval(gameLoop);
    clearInterval(sunDropInterval);
    clearInterval(naturalSunInterval);
});
</script>

<style scoped>
.game-container {
    margin: 0;
    padding: 0;
    width: 100vw;
    height: 120vh;
    background: #87ceeb;
    display: flex;
    flex-direction: column;
    position: relative;
}

.game-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 20px;
    background: rgba(0, 0, 0, 0.5);
    color: white;
    font-size: 24px;
}

.game-controls {
    display: flex;
    gap: 10px;
}

.control-btn {
    padding: 8px 16px;
    font-size: 16px;
    background: #4caf50;
    color: white;
    border: none;
    border-radius: 5px;
    cursor: pointer;
}

.control-btn:hover {
    background: #45a049;
}

.game-board {
    display: flex;
    flex: 1;
    padding: 20px;
    gap: 20px;
    background: #87ceeb;
}

.plant-selector {
    width: 120px;
    max-height: 80vh;
    overflow-y: auto;
    background: rgba(0, 0, 0, 0.3);
    padding: 10px;
    border-radius: 10px;
    display: flex;
    flex-direction: column;
    gap: 10px;
}

.plant-card {
    width: 80px;
    height: 120px;
    background: white;
    border-radius: 5px;
    cursor: pointer;
    position: relative;
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    padding: 5px;
}

.plant-card.disabled {
    opacity: 0.5;
    cursor: not-allowed;
}

.plant-card img {
    width: 60px;
    height: 60px;
    object-fit: contain;
}

.cost {
    position: absolute;
    bottom: 5px;
    right: 5px;
    background: #000;
    color: white;
    padding: 2px 5px;
    border-radius: 3px;
    font-size: 12px;
}

.game-grid {
    flex: 1;
    background: rgba(0, 0, 0, 0.2);
    border-radius: 10px;
    padding: 10px;
    position: relative;
    height: 80vh;
}

.grid-row {
    display: flex;
    height: 20%;
}

.grid-cell {
    flex: 1;
    border: 1px solid rgba(255, 255, 255, 0.2);
    cursor: pointer;
    position: relative;
}

.grid-cell:hover {
    background: rgba(255, 255, 255, 0.1);
}

.game-over {
    position: absolute;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
    background: rgba(0, 0, 0, 0.8);
    color: white;
    padding: 20px;
    border-radius: 10px;
    text-align: center;
}

.restart-btn {
    margin-top: 10px;
    padding: 10px 20px;
    font-size: 16px;
    background: #4caf50;
    color: white;
    border: none;
    border-radius: 5px;
    cursor: pointer;
}

.restart-btn:hover {
    background: #45a049;
}

.plant-name {
    font-size: 12px;
    font-weight: bold;
    margin-top: 5px;
    text-align: center;
}

.plant-description {
    font-size: 10px;
    color: #666;
    text-align: center;
    margin-top: 2px;
}
</style>
